//
//  LeWindow.cpp
//  Leste
//
//  Created by 王乐 on 2022/1/27.
//

#include "LeWindow.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "LeInput.h"
#include "LeScreenSettings.h"
#include <iostream>

LeWindow::LeWindow() {
    
}

LeWindow::~LeWindow() {
    
}

void framebuffer_size_callback(GLFWwindow *window, int width, int height) {
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

void mouse_callback(GLFWwindow *window, double xpos, double ypos) {
    LeInput::mouse_callback(xpos, ypos);
}

void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
    LeInput::scroll_callback(xoffset, yoffset);
}

int LeWindow::initWindow() {
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

    // glfw window creation
    // --------------------
    window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Leste", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);
    
//    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    
    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }
    
    return 1;
}

void LeWindow::configureGlobalOpenGLState() {
    // configure global opengl state
    // -----------------------------
    glEnable(GL_DEPTH_TEST);
//    glEnable(GL_FRAMEBUFFER_SRGB);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

bool LeWindow::shouldCloseWindow() { 
    return glfwWindowShouldClose(window);
}

void LeWindow::setShouldCloseWindow(bool bclose) { 
    glfwSetWindowShouldClose(window, bclose);
}

void LeWindow::configureRenderingOpenGL(float r, float g, float b, float a) {
    glClearColor(r, g, b, a);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

void LeWindow::swapWindowBuffers() { 
    glfwSwapBuffers(window);
}

void LeWindow::pollWindowEvents() { 
    glfwPollEvents();
}

void LeWindow::terminateWindow() { 
    glfwTerminate();
}

GLFWwindow *LeWindow::getWindow() { 
    return window;
}
